from django.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields import *

class BaseId( models.Model ):
    id = UUIDField( max_length = 36, primary_key = True )
    class Meta:
        abstract = True

class FriendshipManager( models.Manager ):
    def friends_for_user( self, user ):
        friends = []
        for friendship in self.filter(from_user=user).select_related(depth=1):
            friends.append({"friend": friendship.to_user, "friendship": friendship})
        for friendship in self.filter(to_user=user).select_related(depth=1):
            friends.append({"friend": friendship.from_user, "friendship": friendship})
        return friends
    def are_friends(self, user1, user2):
        if self.filter(from_user=user1, to_user=user2).count() > 0:
            return True
        if self.filter(from_user=user2, to_user=user1).count() > 0:
            return True
        return False
    def remove(self, user1, user2):
        if self.filter(from_user=user1, to_user=user2):
            friendship = self.filter(from_user=user1, to_user=user2)
        elif self.filter(from_user=user2, to_user=user1):
            friendship = self.filter(from_user=user2, to_user=user1)
        friendship.delete()

# --
# A friendship is a bi-directional association between two users who
# have both agreed to the association.
class Friendship( BaseId ):
    to_user = models.ForeignKey( User, related_name = "friends" )
    from_user = models.ForeignKey( User, related_name = "_unused_" )
    objects = FriendshipManager()
    class Meta:
        unique_together = ( ( 'to_user', 'from_user' ), )
# FIXME
class Event( BaseId ):
    TYPE_CHOICES = (
        ( '1', 'Become Friends' ),
        ( '2', 'Join Theme Group' ),
        ( '3', 'Upload Achievements' ),
        ( '4', 'Share Resources' ),
    )
    user = models.ForeignKey( User )
    type = models.CharField( max_length = 1, choices = TYPE_CHOICES )
    content = models.TextField()
    create_time = models.DateTimeField()

class Message( BaseId ):
    to_user = models.ForeignKey( User, related_name = 'owned_by' )
    from_user = models.ForeignKey( User, related_name = 'created_by' )
    content = models.TextField()
    create_time = models.DateTimeField()

class SendLetter( BaseId ):
    sender = models.ForeignKey( User )
    title = models.CharField( max_length = 100 )
    content = models.TextField()
    send_time = models.DateTimeField()
    issystem = models.BooleanField()
    isdelete = models.BooleanField()

class ReceiveLetter( BaseId ):
    send_letter = models.ForeignKey( SendLetter )
    receiver = models.ForeignKey( User )
    isread = models.BooleanField();
    receive_time = models.DateTimeField()
    isdelete = models.BooleanField()



